home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8234 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  40 lines

  1. Path: news.production.compuserve.com!news
  2. From: John Puopolo <102262.612@CompuServe.COM>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Dynamic Array Allocation With new/delete
  5. Date: 15 Feb 1996 22:49:14 GMT
  6. Organization: Lotus Development Corporation
  7. Message-ID: <4g0d9a$3h6$1@mhadg.production.compuserve.com>
  8. References: <+4bExc9nXQoO083yn@mbnet.mb.ca>
  9.  
  10. Nathan...One method to do what you want is to use "placement 
  11. new."  This consists of allocating a buffer (using operator new) 
  12. that can hold the things you want.  You then create the objects 
  13. "in" the buffer.  
  14.  
  15. For example, let's suppose I want to allocate enough memory to 
  16. hold 10 Radio objects....
  17.  
  18. int main()  {
  19.    // alloc block of memory large enough to hold 10 Radios
  20.        char* buf = new unsigned char[sizeof(Radio) * 10];
  21.      
  22.    // alloc a single Radio object in the buffer
  23.        Radio* pRadio = new (buf) Radio;
  24. }
  25. This says "create a Radio object at memory location buf."  To 
  26. create the next Radio... 
  27.  
  28. Radio* pRadio2 = new (buf + sizeof(Radio)) Radio;  // ...etc.
  29.  
  30. NOTE:  Must use placement delete:  i.e., must delete via 
  31.        pRadio2->~Radio()...true for any object created via   
  32.        placement new.
  33.  
  34. Hope this helps... John  
  35.  
  36. -- 
  37. John Puopolo, Lotus Development Corporation
  38. 102262,612 or jpuopolo@crd.lotus.com
  39. "Knowledge itself is power."
  40.